package com.san.andoid.displayinfo;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.preference.PreferenceManager;
import android.util.DisplayMetrics;
import android.widget.RemoteViews;

public class DisplayInfoWidgetProvider extends AppWidgetProvider {
	String resolutionString, dpiString;

	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager,
			int[] appWidgetIds) {
		super.onUpdate(context, appWidgetManager, appWidgetIds);
		if (resolutionString == null || dpiString == null) {
			SharedPreferences defaultSharedPreferences = PreferenceManager
					.getDefaultSharedPreferences(context);
			int densityDpi = defaultSharedPreferences.getInt(Prefs.ddpi, 0);
			String dpiText = densityDpi == DisplayMetrics.DENSITY_DEFAULT ? "default"
					: densityDpi == DisplayMetrics.DENSITY_HIGH ? "hdpi"
							: densityDpi == DisplayMetrics.DENSITY_LOW ? "ldpi"
									: densityDpi == DisplayMetrics.DENSITY_MEDIUM ? "mdpi"
											: "nodpi";
			String screenSizeText = "";
			int screenSize = context.getResources().getConfiguration().screenLayout
					& Configuration.SCREENLAYOUT_SIZE_MASK;
			screenSizeText = screenSize == Configuration.SCREENLAYOUT_SIZE_LARGE ? "Large"
					: screenSize == Configuration.SCREENLAYOUT_SIZE_NORMAL ? "Normal"
							: screenSize == Configuration.SCREENLAYOUT_SIZE_SMALL ? "Small"
									: screenSize == Configuration.SCREENLAYOUT_SIZE_UNDEFINED ? "Undefined"
											: "not available";

			dpiString = (int)defaultSharedPreferences.getFloat(Prefs.dpix, 0) + ","
					+ (int)defaultSharedPreferences.getFloat(Prefs.dpiy, 0) + " ("
					+ dpiText + ")";
			resolutionString = defaultSharedPreferences.getString(Prefs.sr, "")+" ("+screenSizeText+")";
			Intent intent = new Intent(context, DisplayPrefsActivity.class);
			PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
					intent, 0);
			for (int i = 0; i < appWidgetIds.length; i++) {
				RemoteViews views = new RemoteViews(context.getPackageName(),
						R.layout.widget_layout);
				views.setOnClickPendingIntent(R.id.layout1, pendingIntent);
				views.setTextViewText(R.id.textView1, resolutionString);
				views.setTextViewText(R.id.textView2, dpiString);
				appWidgetManager.updateAppWidget(appWidgetIds[i], views);
			}

		}
	}
}
